/*
 *   Copyright 2012, Thomas Kerber
 *
 *   Licensed under the Apache License, Version 2.0 (the "License");
 *   you may not use this file except in compliance with the License.
 *   You may obtain a copy of the License at
 *
 *       http://www.apache.org/licenses/LICENSE-2.0
 *
 *   Unless required by applicable law or agreed to in writing, software
 *   distributed under the License is distributed on an "AS IS" BASIS,
 *   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *   See the License for the specific language governing permissions and
 *   limitations under the License.
 */
package milk.jpatch.code;

import milk.jpatch.CPoolMap;
import milk.jpatch.attribs.AttributesPatch;

import org.apache.bcel.classfile.Attribute;
import org.apache.bcel.classfile.Code;

/**
 * Patch denoting the replacement of the code attribute.
 * @author Thomas Kerber
 * @version 1.0.0
 */
public class CodeReplace extends CodePatch{
    
    private static final long serialVersionUID = -6529941890852822270L;
    
    /**
     * The code to replace with.
     * 
     * Note the the attributes of this <strong>are ignored</strong>
     */
    private Code replaceWith;
    
    /**
     * Creates.
     * @param attribPatch The component attributes patch.
     * @param replacer The replacement code object. The attributes of this are
     *     ignored.
     */
    public CodeReplace(AttributesPatch attribPatch, Code replacer){
        super(attribPatch);
        // Attributes are stored seperately, so we may as well throw them out
        // here.
        replacer.setAttributes(new Attribute[0]);
        replaceWith = replacer;
    }
    
    @Override
    public Code patch(Code c, CPoolMap map){
        Code newCode = map.applyTo(replaceWith, newCPs);
        // Retain old attributes for now.
        newCode.setAttributes(c.getAttributes());
        // Set all old code CPs to 0.
        for(CodePointHook cph : oldCPs)
            cph.codePoint = 0;
        return newCode;
    }
    
}
